﻿#include <stdio.h>  //fgets
#include <string.h> //strlen
#include <curl/curl.h> //libcurl
#include "cJSON.h"

/*
构造JSON请求报文
{
    "perception": {
        "inputText": {
            "text": "你好"
        },
    },
    "userInfo": {
        "apiKey": "16bd987463b64d7fa1b75360899ba92d",
        "userId": "tianjingchen"
    }
} 
*/
char* robot_make_request(const char* apikey, const char* text)
{
    //判断输入的字符串长度不为0
     if (strlen(text) == 0)
    {
        return NULL;
    }

    cJSON* request = cJSON_CreateObject();

    cJSON* perception = cJSON_CreateObject();
    cJSON* inputText = cJSON_CreateObject();

    cJSON_AddStringToObject(inputText, "text", text);
    cJSON_AddItemToObject(perception, "inputText", inputText);
    cJSON_AddItemToObject(request, "perception", perception);

    cJSON* userInfo = cJSON_CreateObject();
    cJSON_AddStringToObject(userInfo, "apiKey", apikey);
    cJSON_AddStringToObject(userInfo, "userId", "tianjingchen");
    cJSON_AddItemToObject(request, "userInfo", userInfo);

    //将JSONS数据结构转为字符串
    return cJSON_Print(request);
    
}

//41709030121陈恬静作业
//发送请求报文给图灵机器人服务器，等待服务器的响应报文
char* robot_send_request(const char* request)
{
    FILE* fp;

    //响应消息的地址
    char* response = NULL;
    //响应消息的长度
    size_t resplen = 0;
    //创建内存文件，当通过文件句柄写入数据时，会自动分配内存
    fp = open_memstream(&response, &resplen);
    if (fp == NULL) //打开文件失败，打印错误信息并退出
    {
        perror("open_memstream() failed");
        return NULL;
    }
    //初始化HTTP客户端
    CURL* curl = curl_easy_init();
    
    //准备HTTP请求消息，设置API地址（URI）
    curl_easy_setopt(curl, CURLOPT_URL, "http://openapi.tuling123.com/openapi/api/v2");
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    //配置需要通过POST请求消息发送给服务器的数据
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    //发送HTTP请求消息，等待服务器的响应消息
    CURLcode error = curl_easy_perform(curl);
    if (error != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(error));
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    fclose(fp);
    //释放HTTP客户端申请的资源
    curl_easy_cleanup(curl);
    puts( response);
    return NULL;
}

//图灵机器人API，一次最多可以处理128个字符
#define LINE_LEN 128

//保存输入字符串的缓冲区
char line[LINE_LEN]; 

int main()
{
    //机器人"小陈"
    char* apikey = "16bd987463b64d7fa1b75360899ba92d";
    //从标准输入读取一行字符
    while(fgets(line, LINE_LEN, stdin) != NULL)
    {
        //构造请求报文
        char* request = robot_make_request(apikey, line);
        if (request == NULL)
        {
            continue;
        }
        //将请求报文发送给图灵机器人
        robot_send_request(request);
    }

    return 0;
}